package com.zuul.component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * @ClassName: MyCustomFilter
 * @Author: ZhangYue26
 * @Description: 自定义过滤器实现
 * @Date: 2021-01-14
 */
@Component
public  class MyCustomFilter extends ZuulFilter {

    /**
      * @Description 过滤器类型，四种，pre、routing、post、error
      * @author ZhangYue26
      * @date 2021/1/14
      * @param []
      * @return java.lang.String
      **/
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
      * @Description 过滤顺序为int值，值越小越早执行
      * @author ZhangYue26
      * @date 2021/1/14
      * @param []
      * @return int
      **/
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
      * @Description 表示是否过滤逻辑，如果为true则执行run方法，如果为false则不执行run方法
      * @author ZhangYue26
      * @date 2021/1/14
      * @param []
      * @return boolean
      **/
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
      * @Description run方法内部写具体过滤逻辑
      * @author ZhangYue26
      * @date 2021/1/14
      * @param []
      * @return java.lang.Object
      **/
    @Override
    public Object run() {
        //本方法以验证token为例
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)) {
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            try {
                context.getResponse().getWriter().write("token is Empty");
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}
